package cn.rengy.dsstaticdemo.yzm;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;

@Component
public class ValidateCodeFilter extends OncePerRequestFilter {

	@Autowired private AuthenticationFailureHandler authenticationFailureHandler;

  @Override
  protected void doFilterInternal(
      HttpServletRequest httpServletRequest,
      HttpServletResponse httpServletResponse,
      FilterChain filterChain)
      throws ServletException, IOException {

    if (httpServletRequest.getRequestURI().equals("/user/login")){
        
        try {
        	validateCode(httpServletRequest);
          } catch (ValidateCodeException e) {
            authenticationFailureHandler.onAuthenticationFailure(
                httpServletRequest, httpServletResponse, e);
            return;
          }
    }
    filterChain.doFilter(httpServletRequest, httpServletResponse);
  }

  private void validateCode(HttpServletRequest servletWebRequest)
      throws ServletRequestBindingException {
	  HttpSession session=servletWebRequest.getSession();
    ImageCode codeInSession =
        (ImageCode)
        session.getAttribute(ValidateController.SESSION_KEY_IMAGE_CODE);
    String codeInRequest =
        ServletRequestUtils.getStringParameter(servletWebRequest, "imageCode");
    if (codeInRequest==null) {
    	session.setAttribute("msg", "验证码不能为空！");
      throw new ValidateCodeException("验证码不能为空！");
      
    }
    if (codeInSession == null) {
    	session.setAttribute("msg", "验证码不存在！");
      throw new ValidateCodeException("验证码不存在！");
    }
    if (codeInSession.isExpire()) {
    	session.setAttribute("msg", "验证码已过期！");
    	session.removeAttribute( ValidateController.SESSION_KEY_IMAGE_CODE);
      throw new ValidateCodeException("验证码已过期！");
    }
    if (!codeInSession.getCode().equalsIgnoreCase(codeInRequest)) {
    	session.setAttribute("msg", "验证码不正确！");
      throw new ValidateCodeException("验证码不正确！");
    }
    session.removeAttribute( ValidateController.SESSION_KEY_IMAGE_CODE);
  }
}
